<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>

  <body>
    <script>
      // 一 、Promise.all() : 可以执行多个promise对象，获取promise对象的结果
      // all是同时执行promise对象
      // all 收集的结果，必须都是成功的 ，如果失败了就收集不到最终的结果

      // Promise.all的实现

      class MyPromise {
        static all(arr) {
          return new Promise((resolve, reject) => {
            let count = 0;
            let newArr = new Array(arr.length);
            arr.forEach((item, key) => {
              item.then(
                (res) => {
                  newArr[key] = res;
                  count++;
                  if (count === arr.length) {
                    resolve(newArr);
                  }
                },
                (err) => {
                  // 如果失败了，直接调用reject；
                  reject(err);
                }
              );
            });
          });
        }
      }

      let p1 = new Promise((resolve, reject) => {
        setTimeout(() => {
          resolve(111);
        }, 2000);
      });

      let p2 = new Promise((resolve, reject) => {
        setTimeout(() => {
          resolve(222);
        }, 1000);
      });

      let p3 = new Promise((resolve, reject) => {
        setTimeout(() => {
          resolve(3333);
          // reject("333err");
        }, 2000);
      });

      MyPromise.all([p1, p2, p3]).then(
        (res) => {
          console.log(res);
        },
        (err) => {
          console.log(err);
        }
      );
    </script>
  </body>
</html>
